package com.sensetime.jv.util;

import cn.hutool.extra.spring.SpringUtil;
import com.sensetime.jv.enums.StatusEnum;
import com.sensetime.jv.exception.CustomException;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;

import java.util.concurrent.TimeUnit;


@Slf4j
public class RedisLock {

    private static final RedissonClient redissonClient = SpringUtil.getBean(RedissonClient.class);

    /**
     * 执行需要加锁的业务逻辑，支持重试机制
     * @param lockName 锁名称
     * @param action 需要执行的业务逻辑
     */
    public static void executeWithLock(String lockName, Runnable action) {
        String lockKey = lockName;
        RLock rLock = redissonClient.getLock(lockKey);

        try {
            // 尝试获取锁，等待时间 30 秒，锁持有时间 60 秒
            if (rLock.tryLock(30, 60, TimeUnit.SECONDS)) {
                try {
                    action.run(); // 执行业务逻辑
                } finally {
                    rLock.unlock(); // 释放锁
                }
            } else {
                log.error("锁状态异常,请检查: {}", lockKey);
                throw new CustomException(StatusEnum.BAD_REQUEST);
            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            log.error("锁状态异常: {}", lockKey, e);
            throw new CustomException(StatusEnum.BAD_REQUEST);
        }
    }
}